package com.example.screenrecorder;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;

import androidx.core.app.NotificationCompat;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 高级屏幕录制服务 - 支持双引擎录制的专业级录制服务
 * 功能特性：
 * - 标准引擎：适合一般录制需求
 * - 高级引擎：支持暂停续录、分段录制、时间轴标记
 * - 多种分辨率和帧率支持
 * - 音频录制控制
 * - 前台服务保证录制稳定性
 */
public class AdvancedScreenRecordService extends Service {
    
    // ========== 日志标签 ==========
    private static final String TAG = "AdvancedScreenRecordService";
    
    // ========== 服务动作常量 ==========
    public static final String ACTION_START_RECORDING = "start_recording";    // 开始录制动作
    public static final String ACTION_STOP_RECORDING = "stop_recording";      // 停止录制动作
    public static final String ACTION_PAUSE_RECORDING = "pause_recording";   // 暂停录制动作
    public static final String ACTION_RESUME_RECORDING = "resume_recording"; // 恢复录制动作
    
    // ========== Intent参数常量 ==========
    public static final String EXTRA_RESULT_CODE = "result_code"; // 结果代码参数
    public static final String EXTRA_RESULT_DATA = "result_data"; // 结果数据参数
    
    // ========== 通知相关常量 ==========
    private static final String NOTIFICATION_CHANNEL_ID = "advanced_screen_recording_channel"; // 通知渠道ID
    private static final int NOTIFICATION_ID = 1002; // 通知ID
    
    // ========== 核心录制组件 ==========
    private MediaProjection mediaProjection;           // 媒体投影对象，用于屏幕捕获
    private MediaRecorder mediaRecorder;               // 媒体录制器，负责音视频编码
    private VirtualDisplay virtualDisplay;             // 虚拟显示器，连接屏幕和录制器
    private MediaProjectionManager mediaProjectionManager; // 媒体投影管理器
    
    // ========== 配置和状态管理 ==========
    private RecordingConfig config;                   // 录制配置对象
    private List<RecordingSegment> recordingSegments; // 录制段列表（高级引擎用）
    private RecordingSegment currentSegment;          // 当前录制段
    
    // ========== 录制状态变量 ==========
    private static boolean isRecording = false;       // 录制状态标志
    private static boolean isPaused = false;          // 暂停状态标志
    private String outputPath;                        // 输出文件路径
    private long startTime;                           // 录制开始时间
    private long pausedTime = 0;                      // 暂停时间累计
    
    /**
     * 服务创建时的初始化方法
     * 初始化媒体投影管理器、录制段列表和通知渠道
     */
    @Override
    public void onCreate() {
        super.onCreate();
        // 获取媒体投影管理器，用于创建屏幕录制会话
        mediaProjectionManager = (MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE);
        // 初始化录制段列表，用于高级引擎的分段录制
        recordingSegments = new ArrayList<>();
        // 创建通知渠道，用于显示录制状态
        createNotificationChannel();
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            String action = intent.getAction();
            if (ACTION_START_RECORDING.equals(action)) {
                int resultCode = intent.getIntExtra(EXTRA_RESULT_CODE, 0);
                Intent resultData = intent.getParcelableExtra(EXTRA_RESULT_DATA);
                startRecording(resultCode, resultData);
            } else if (ACTION_STOP_RECORDING.equals(action)) {
                stopRecording();
            } else if (ACTION_PAUSE_RECORDING.equals(action)) {
                pauseRecording();
            } else if (ACTION_RESUME_RECORDING.equals(action)) {
                resumeRecording();
            }
        }
        return START_STICKY;
    }
    
    private void startRecording(int resultCode, Intent resultData) {
        if (isRecording) {
            return;
        }
        
        try {
            // 加载配置
            loadRecordingConfig();
            
            // 创建MediaProjection
            mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, resultData);
            
            // 根据引擎类型选择录制方式
            if (config.getEngine() == RecordingConfig.RecordingEngine.ADVANCED) {
                startAdvancedRecording();
            } else {
                startStandardRecording();
            }
            
            isRecording = true;
            startTime = System.currentTimeMillis();
            
            // 显示前台通知
            startForeground(NOTIFICATION_ID, createNotification());
            
            Log.d(TAG, "Advanced screen recording started");
            
        } catch (Exception e) {
            Log.e(TAG, "Error starting advanced screen recording", e);
            stopSelf();
        }
    }
    
    private void startStandardRecording() throws IOException {
        setupMediaRecorder();
        createVirtualDisplay();
        mediaRecorder.start();
    }
    
    private void startAdvancedRecording() throws IOException {
        // 高级引擎：支持分段录制
        createNewSegment();
        setupMediaRecorder();
        createVirtualDisplay();
        mediaRecorder.start();
    }
    
    private void createNewSegment() {
        currentSegment = new RecordingSegment();
        currentSegment.startTime = System.currentTimeMillis();
        recordingSegments.add(currentSegment);
    }
    
    private void pauseRecording() {
        if (!isRecording || isPaused) {
            return;
        }
        
        try {
            if (config.getEngine() == RecordingConfig.RecordingEngine.ADVANCED) {
                // 高级引擎：暂停当前段，准备新段
                mediaRecorder.stop();
                mediaRecorder.release();
                
                currentSegment.endTime = System.currentTimeMillis();
                currentSegment.duration = currentSegment.endTime - currentSegment.startTime;
                
                isPaused = true;
                updateNotification("录制已暂停");
                
                Log.d(TAG, "Recording paused - segment duration: " + currentSegment.duration + "ms");
            }
        } catch (Exception e) {
            Log.e(TAG, "Error pausing recording", e);
        }
    }
    
    private void resumeRecording() {
        if (!isRecording || !isPaused) {
            return;
        }
        
        try {
            if (config.getEngine() == RecordingConfig.RecordingEngine.ADVANCED) {
                // 创建新段
                createNewSegment();
                setupMediaRecorder();
                createVirtualDisplay();
                mediaRecorder.start();
                
                isPaused = false;
                updateNotification("录制已恢复");
                
                Log.d(TAG, "Recording resumed - new segment started");
            }
        } catch (Exception e) {
            Log.e(TAG, "Error resuming recording", e);
        }
    }
    
    private void stopRecording() {
        if (!isRecording) {
            return;
        }
        
        try {
            if (mediaRecorder != null) {
                mediaRecorder.stop();
                mediaRecorder.release();
                mediaRecorder = null;
            }
            
            if (virtualDisplay != null) {
                virtualDisplay.release();
                virtualDisplay = null;
            }
            
            if (mediaProjection != null) {
                mediaProjection.stop();
                mediaProjection = null;
            }
            
            // 处理分段录制
            if (config.getEngine() == RecordingConfig.RecordingEngine.ADVANCED) {
                processSegmentedRecording();
            }
            
            isRecording = false;
            isPaused = false;
            
            // 停止前台服务
            stopForeground(true);
            stopSelf();
            
            Log.d(TAG, "Advanced screen recording stopped");
            
        } catch (Exception e) {
            Log.e(TAG, "Error stopping advanced screen recording", e);
        }
    }
    
    private void processSegmentedRecording() {
        // 处理分段录制，生成时间轴标记
        long totalDuration = 0;
        for (RecordingSegment segment : recordingSegments) {
            totalDuration += segment.duration;
            Log.d(TAG, "Segment: " + segment.startTime + " - " + segment.endTime + " (" + segment.duration + "ms)");
        }
        
        // 这里可以生成时间轴文件或进行视频合并
        Log.d(TAG, "Total recording duration: " + totalDuration + "ms");
    }
    
    private void loadRecordingConfig() {
        SharedPreferences prefs = getSharedPreferences("screen_recorder_settings", MODE_PRIVATE);
        config = new RecordingConfig();
        
        // 加载基本设置
        config.setAudioEnabled(SettingsActivity.isAudioEnabled(prefs));
        config.setQuality(RecordingConfig.VideoQuality.values()[SettingsActivity.getVideoQuality(prefs)]);
        
        // 加载高级设置
        config.setEngine(RecordingConfig.RecordingEngine.values()[
            prefs.getInt("recording_engine", 0)]);
        config.setResolution(RecordingConfig.Resolution.values()[
            prefs.getInt("recording_resolution", 1)]);
        config.setFrameRate(RecordingConfig.FrameRate.values()[
            prefs.getInt("recording_framerate", 2)]);
        config.setPauseResumeEnabled(prefs.getBoolean("pause_resume_enabled", false));
        config.setAnnotationEnabled(prefs.getBoolean("annotation_enabled", false));
        config.setCameraEnabled(prefs.getBoolean("camera_enabled", false));
    }
    
    private void setupMediaRecorder() throws IOException {
        mediaRecorder = new MediaRecorder();
        
        // 设置音频源
        if (config.isAudioEnabled()) {
            mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        }
        
        // 设置视频源
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
        
        // 设置输出格式
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        
        // 设置编码器
        mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        if (config.isAudioEnabled()) {
            mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        }
        
        // 设置视频参数
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        int width = config.getActualWidth(metrics.widthPixels);
        int height = config.getActualHeight(metrics.heightPixels);
        
        mediaRecorder.setVideoSize(width, height);
        mediaRecorder.setVideoFrameRate(config.getFrameRate().value);
        mediaRecorder.setVideoEncodingBitRate(config.getBitrate());
        
        // 设置音频参数
        if (config.isAudioEnabled()) {
            mediaRecorder.setAudioSamplingRate(44100);
            mediaRecorder.setAudioEncodingBitRate(128000);
            mediaRecorder.setAudioChannels(2);
        }
        
        // 设置输出文件
        outputPath = createOutputPath();
        mediaRecorder.setOutputFile(outputPath);
        
        mediaRecorder.prepare();
    }
    
    private void createVirtualDisplay() {
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        int width = config.getActualWidth(metrics.widthPixels);
        int height = config.getActualHeight(metrics.heightPixels);
        int density = metrics.densityDpi;
        
        virtualDisplay = mediaProjection.createVirtualDisplay(
                "AdvancedScreenRecord",
                width, height, density,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR,
                mediaRecorder.getSurface(),
                null, null
        );
    }
    
    private String createOutputPath() {
        File moviesDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
        File screenRecordDir = new File(moviesDir, "AdvancedScreenRecord");
        if (!screenRecordDir.exists()) {
            screenRecordDir.mkdirs();
        }
        
        String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String engineSuffix = config.getEngine() == RecordingConfig.RecordingEngine.ADVANCED ? "_advanced" : "_standard";
        return new File(screenRecordDir, "screen_record_" + timestamp + engineSuffix + ".mp4").getAbsolutePath();
    }
    
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    NOTIFICATION_CHANNEL_ID,
                    "Advanced Screen Recording",
                    NotificationManager.IMPORTANCE_LOW
            );
            channel.setDescription("Advanced screen recording notification");
            
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
    
    private Notification createNotification() {
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
        );
        
        Intent stopIntent = new Intent(this, AdvancedScreenRecordService.class);
        stopIntent.setAction(ACTION_STOP_RECORDING);
        PendingIntent stopPendingIntent = PendingIntent.getService(
                this, 0, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
        );
        
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
                .setContentTitle("高级屏幕录制中")
                .setContentText("引擎: " + config.getEngine().name + " | 质量: " + config.getQuality().name)
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentIntent(pendingIntent)
                .addAction(R.drawable.ic_launcher_foreground, "停止", stopPendingIntent)
                .setOngoing(true);
        
        // 如果是高级引擎且支持暂停，添加暂停按钮
        if (config.getEngine() == RecordingConfig.RecordingEngine.ADVANCED && config.isPauseResumeEnabled()) {
            Intent pauseIntent = new Intent(this, AdvancedScreenRecordService.class);
            pauseIntent.setAction(isPaused ? ACTION_RESUME_RECORDING : ACTION_PAUSE_RECORDING);
            PendingIntent pausePendingIntent = PendingIntent.getService(
                    this, 0, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE
            );
            
            String pauseText = isPaused ? "继续" : "暂停";
            builder.addAction(R.drawable.ic_launcher_foreground, pauseText, pausePendingIntent);
        }
        
        return builder.build();
    }
    
    private void updateNotification(String status) {
        Notification notification = createNotification();
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.notify(NOTIFICATION_ID, notification);
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        stopRecording();
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    
    public static boolean isRecording() {
        return isRecording;
    }
    
    public static boolean isPaused() {
        return isPaused;
    }
    
    // 录制段类
    private static class RecordingSegment {
        long startTime;
        long endTime;
        long duration;
    }
}
